from django_redis import get_redis_connection
from rest_framework import serializers
import re

from rest_framework_jwt.settings import api_settings

from .models import User


class CreateUserSerializer(serializers.ModelSerializer):
    """注册序列化器"""
    #补充模型类以外的映射字段
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)

    #增加ｔｏｋｅｎ
    token = serializers.CharField(label='登录状态token',read_only=True)

    class Meta:
        model = User
        fields = ['id','username','mobile','password','password2','allow','sms_code','token']
        #只输出：user  password token
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self,value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$',value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def validated_allow(self,value):
        """检测用户是否同意协议"""
        if value != True:
            raise serializers.ValidationError('请勾选同意协议')



    def validate(self, attrs):
        """判断两次密码是否一致"""
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两次密码不一致')

        #判断短信验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile =attrs['mobile']
        real_sms_code = redis_conn.get('sms_%s'%mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')
        return attrs

    def create(self, validated_data):
        """重写新增数据的方法"""
        #移除三个不需要存数的字段
        del validated_data['password2']
        del validated_data['allow']
        del validated_data['sms_code']

        #保存用户数据
        user = User.objects.create(**validated_data)

        user.set_password(validated_data.get('password'))
        user.save()

        #在注册成功之后，响应注册结束之前，生成JWT token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token
        return user







